//
//  HJSupportInputBar.m
//  KaiChat
//
//  Created by lx on 2023/12/22.
//

#import "HJSupportInputBar.h"
#import "NSString+emoji.h"
#import "TUIDefine.h"
#import "HJResponderTextView.h"
#import "TUIDefine.h"
#import "UIView+TUILayout.h"
#import "HJGradientButton.h"
#import "HJAlertController.h"
#import "NSString+QMUI.h"
#import <MBProgressHUD.h>


@interface HJSupportInputBar() <UITextViewDelegate>

@property (nonatomic, assign) BOOL isFocusOn;
@property (nonatomic, assign) NSInteger maximumTextLength;
@property (nonatomic, assign) long long lastTimestamp;

@end

@implementation HJSupportInputBar


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        [self setupViews];
        [self defaultLayout];
    }
    return self;
}

- (void)setupViews
{
    
    self.maximumTextLength = 2048;
    
    _lineView = [[UIView alloc] init];
    _lineView.backgroundColor = UIColor.tj_FFFFFFColor;
    
    _FAQButton = [[UIButton alloc] init];
    [_FAQButton setImage:[UIImage imageNamed:@"input_bar_FQA"] forState:UIControlStateNormal];
    [_FAQButton addTarget:self action:@selector(clickFAQButton:) forControlEvents:UIControlEventTouchUpInside];
    _FAQButton.hidden = YES;
    [self addSubview:_FAQButton];
    
    _keyboardButton = [[UIButton alloc] init];
    [_keyboardButton addTarget:self action:@selector(clickKeyboardBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_keyboardButton setImage:[UIImage imageNamed:@"input_bar_keyboard"] forState:UIControlStateNormal];
    [self addSubview:_keyboardButton];
    
    
    _sendButton = [[UIButton alloc] init];
    _sendButton.hidden = YES;
    [_sendButton addTarget:self action:@selector(clickSendBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_sendButton setImage:[UIImage imageNamed:@"input_bar_send_select"] forState:UIControlStateNormal];
    _sendButton.backgroundColor = UIColor.whiteColor;
    [self addSubview:_sendButton];
    
    _FAQContentButton = [HJStyle2Button buttonWithSuperView:self font:UIFontMediumMake(14) color:UIColor.tj_1D0061Color title:nil];
    [_FAQContentButton addTarget:self action:@selector(didClickFAQContentButton) forControlEvents:UIControlEventTouchUpInside];
    [_FAQContentButton setTitle:@"FAQ" forState:UIControlStateNormal];
    _FAQContentButton.addCornerRadius(10);
    
    _inputTextView = [[HJResponderTextView alloc] init];
    _inputTextView.delegate = self;
    _inputTextView.placeholder = @"Message";
    _inputTextView.hidden = YES;
    CGFloat topMargin = (TTextView_TextView_Height_Min - ceilf(UIFontMake(14).lineHeight)) * 0.5;
    _inputTextView.textContainerInset = UIEdgeInsetsMake(topMargin, 10, 10, 10);
    [_inputTextView setFont:UIFontMake(14)];
    _inputTextView.tintColor = UIColor.tj_cursorColor;
    _inputTextView.backgroundColor = UIColor.tj_F6F6F6Color;
    _inputTextView.textColor = UIColor.tj_333333Color;
    [_inputTextView setReturnKeyType:UIReturnKeySend];
    _inputTextView.addCornerRadius(10);
    [self addSubview:_inputTextView];
}

- (void)defaultLayout {
    _lineView.frame = CGRectMake(0, 0, Screen_Width, TLine_Heigh);
    CGSize buttonSize = TTextView_Button_Size;
    CGFloat buttonOriginY = (TTextView_Height - buttonSize.height) * 0.5;
    _FAQButton.frame = CGRectMake(TTextView_Margin, buttonOriginY, buttonSize.width, buttonSize.height);
    _keyboardButton.frame = _FAQButton.frame;
    
    _sendButton.frame = CGRectMake(Screen_Width - buttonSize.width - TTextView_Margin, buttonOriginY, buttonSize.width, buttonSize.height);
    
    CGFloat beginX = _FAQButton.frame.origin.x + _FAQButton.frame.size.width + TTextView_Margin;
    CGFloat endX =  KScreenWidth - leftRightMargin;
    
    _FAQContentButton.frame = CGRectMake(beginX, (TTextView_Height - TTextView_TextView_Height_Min) * 0.5, endX - beginX, TTextView_TextView_Height_Min);
    _inputTextView.frame = _FAQContentButton.frame;
    
    [self.placeholderLabel sizeToFit];
    
    _placeholderLabel.frame = CGRectMake(4, 10, self.placeholderLabel.tj_size.width, self.placeholderLabel.tj_size.height);
}

- (void)layoutButton:(CGFloat)height
{
    CGRect frame = self.frame;
    CGFloat offset = height - frame.size.height;
    frame.size.height = height;
    self.frame = frame;
    
    CGSize buttonSize = TTextView_Button_Size;
    CGFloat bottomMargin = (TTextView_Height - buttonSize.height) * 0.5;
    CGFloat originY = frame.size.height - buttonSize.height - bottomMargin;
    
    CGRect sendButtonFrame = _sendButton.frame;
    sendButtonFrame.origin.y = originY;
    _sendButton.frame = sendButtonFrame;
    
    CGRect voiceFrame = _FAQButton.frame;
    voiceFrame.origin.y = originY;
    _FAQButton.frame = voiceFrame;
    
    _keyboardButton.frame = _FAQButton.frame;
    
    if(_delegate && [_delegate respondsToSelector:@selector(inputBar:didChangeInputHeight:)]){
        [_delegate inputBar:self didChangeInputHeight:offset];
    }
}

- (void)clickSendBtn:(UIButton *)sender {
    [self sendTextWithTextView:self.inputTextView];
}

- (void)clickFAQButton:(UIButton *)sender {
    _FAQButton.hidden = YES;
    _keyboardButton.hidden = NO;
    _FAQContentButton.hidden = NO;
    _inputTextView.hidden = YES;
    _sendButton.hidden = YES;
    [_inputTextView resignFirstResponder];
    [self layoutButton:TTextView_Height];

    if(_delegate && [_delegate respondsToSelector:@selector(inputBarDidClickFAQButton:)]){
        [_delegate inputBarDidClickFAQButton:self];
    }
}

- (void)didClickFAQContentButton {
    
    NSTimeInterval timestamp = [NSDate date].timeIntervalSince1970;
    if (_lastTimestamp > 0 && timestamp - _lastTimestamp <= 2) {
        MBProgressHUD *messageHud = [HJHUD getShowMessageHud];
        if (messageHud && [messageHud.detailsLabel.text isEqualToString:@"Frequent operations"]) {
            return;
        }
        [HJHUD showMessage:@"Frequent operations"];
        return;
    }
    
    _lastTimestamp = timestamp;
    if(_delegate && [_delegate respondsToSelector:@selector(inputBarDidClickFAQContentButton:)]){
        [_delegate inputBarDidClickFAQContentButton:self];
    }
}


- (void)clickKeyboardBtn:(UIButton *)sender {
    
    _FAQButton.hidden = NO;
    _keyboardButton.hidden = YES;
    _FAQContentButton.hidden = YES;
    _inputTextView.hidden = NO;
    
    if (_inputTextView.text.length) {
        [self showSendButton];
    } else {
        [self hiddenSendButton];
    }
    
    [self layoutButton:_inputTextView.frame.size.height + 2 * TTextView_Margin];
    if(_delegate && [_delegate respondsToSelector:@selector(inputBarDidTouchKeyboard:)]){
        [_delegate inputBarDidTouchKeyboard:self];
    }
}


- (void)showSendButton {
    self.sendButton.hidden = NO;
    self.inputTextView.placeholderLabel.alpha = 0;
    
    CGFloat oldWidth = _inputTextView.frame.size.width;
    
    CGFloat beginX = _FAQButton.frame.origin.x + _FAQButton.frame.size.width + TTextView_Margin;
    CGFloat endX =  KScreenWidth - leftRightMargin - _sendButton.tj_width;
    CGFloat newWidth = endX - beginX;
    if(oldWidth == newWidth){
        return;
    }
    
    CGRect sendButtonFrame = self.inputTextView.frame;
    sendButtonFrame.size.width = newWidth;
    self.inputTextView.frame = sendButtonFrame;
    
}

- (void)hiddenSendButton {
    self.sendButton.hidden = YES;
    self.inputTextView.placeholderLabel.alpha = 1;
    
    CGFloat oldWidth = _inputTextView.frame.size.width;
    CGFloat beginX = _FAQButton.frame.origin.x + _FAQButton.frame.size.width + TTextView_Margin;
    CGFloat endX =  KScreenWidth - leftRightMargin;
    CGFloat newWidth = endX - beginX;
    if(oldWidth == newWidth){
        return;
    }
    
    CGRect sendButtonFrame = self.inputTextView.frame;
    sendButtonFrame.size.width = newWidth;
    self.inputTextView.frame = sendButtonFrame;
}

#pragma mark - talk

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.keyboardButton.hidden = YES;
    self.FAQButton.hidden = NO;
    self.isFocusOn = YES;
    
    if (self.isFocusOn &&[textView.textStorage getPlainString].length > 0) {
        if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldBeginTyping:)]) {
            [_delegate inputTextViewShouldBeginTyping:textView];
        }
    }
    
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    self.isFocusOn = NO;
    if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldEndTyping:)]) {
        [_delegate inputTextViewShouldEndTyping:textView];
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    
    if (textView.text.length) {
        [self showSendButton];
    } else {
        [self hiddenSendButton];
    }
    
    
    if (self.isFocusOn && [textView.textStorage getPlainString].length == 0) {
        if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldEndTyping:)]) {
            [_delegate inputTextViewShouldEndTyping:textView];
        }
    }
    CGSize size = [_inputTextView sizeThatFits:CGSizeMake(_inputTextView.frame.size.width, TTextView_TextView_Height_Max)];
    CGFloat oldHeight = _inputTextView.frame.size.height;
    CGFloat newHeight = size.height;
    
    if(newHeight > TTextView_TextView_Height_Max){
        newHeight = TTextView_TextView_Height_Max;
    }
    if(newHeight < TTextView_TextView_Height_Min){
        newHeight = TTextView_TextView_Height_Min;
    }
    if(oldHeight == newHeight){
        return;
    }
    
    __weak typeof(self) ws = self;
    [UIView animateWithDuration:0.25 animations:^{
        CGRect textFrame = ws.inputTextView.frame;
        textFrame.size.height += newHeight - oldHeight;
        ws.inputTextView.frame = textFrame;
        [ws layoutButton:newHeight + 2 * TTextView_Margin];
    }];
}

- (void)sendTextWithTextView:(UITextView *)textView {
    
    if(_delegate && [_delegate respondsToSelector:@selector(inputBar:didSendText:)]) {
        NSString *sp = [[textView.textStorage getPlainString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (sp.length == 0) {
            [HJAlertController alertInController:self.mm_viewController title:nil message:@"Unable to send blank message" left:nil right:^(HJAlertAction * _Nonnull action) {
                action.title = @"OK";
                action.titleColor = UIColor.tj_mainColor;
            }];
        } else {
            [_delegate inputBar:self didSendText:[textView.textStorage getPlainString]];
            [self clearInput];
        }
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"]){
        [self sendTextWithTextView:textView];
        return NO;
    }
    
    if (self.maximumTextLength < NSUIntegerMax) {
        
        // 如果是中文输入法正在输入拼音的过程中（markedTextRange 不为 nil），是不应该限制字数的（例如输入“huang”这5个字符，其实只是为了输入“黄”这一个字符），所以在 shouldChange 这里不会限制，而是放在 didChange 那里限制。
        if (textView.markedTextRange) {
            return YES;
        }
        
        BOOL isDeleting = range.length > 0 && text.length <= 0;
        if (isDeleting) {
            if (NSMaxRange(range) > textView.text.length) {
                // https://github.com/Tencent/QMUI_iOS/issues/377
                return NO;
            } else {
                return YES;
            }
        }
        
        NSUInteger rangeLength =  range.length;
        BOOL textWillOutofMaximumTextLength = textView.text.length - rangeLength + text.length > self.maximumTextLength;
        if (textWillOutofMaximumTextLength) {
            // 当输入的文本达到最大长度限制后，此时继续点击 return 按钮（相当于尝试插入“\n”），就会认为总文字长度已经超过最大长度限制，所以此次 return 按钮的点击被拦截，外界无法感知到有这个 return 事件发生，所以这里为这种情况做了特殊保护
            if (textView.text.length - rangeLength == self.maximumTextLength && [text isEqualToString:@"\n"]) {
                return NO;
            }
            // 将要插入的文字裁剪成多长，就可以让它插入了
            NSInteger substringLength = self.maximumTextLength - textView.text.length + rangeLength;
            
            if (substringLength > 0 && text.length > substringLength) {
                NSString *allowedText = [text qmui_substringAvoidBreakingUpCharacterSequencesWithRange:NSMakeRange(0, substringLength) lessValue:YES countingNonASCIICharacterAsTwo:NO];
                if (allowedText.length <= substringLength) {
                    textView.text = [textView.text stringByReplacingCharactersInRange:range withString:allowedText];
                    textView.selectedRange = NSMakeRange(range.location + substringLength, 0);
                    
                    if ([textView.delegate respondsToSelector:@selector(textViewDidChange:)]) {
                        [textView.delegate textViewDidChange:textView];
                    }
                }
            }
            return NO;
        }
    }
    
    return YES;
}

- (void)onDeleteBackward:(HJResponderTextView *)textView
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(inputBarDidDeleteBackward:)]) {
        [self.delegate inputBarDidDeleteBackward:self];
    }
}

- (void)clearInput
{
    [_inputTextView.textStorage deleteCharactersInRange:NSMakeRange(0, _inputTextView.textStorage.length)];
    [self textViewDidChange:_inputTextView];
}

- (NSString *)getInput
{
    return [_inputTextView.textStorage getPlainString];
}


- (void)addEmoji:(NSString *)emoji
{
    
    [_inputTextView setText:[_inputTextView.text stringByAppendingString:emoji]];
    if (!_inputTextView.markedTextRange) {
        if (_inputTextView.text.length > self.maximumTextLength) {
            _inputTextView.text = [_inputTextView.text qmui_substringAvoidBreakingUpCharacterSequencesWithRange:NSMakeRange(0, self.maximumTextLength) lessValue:YES countingNonASCIICharacterAsTwo:NO];
            return;
        }
    }
    
    if(_inputTextView.contentSize.height > TTextView_TextView_Height_Max){
        float offset = _inputTextView.contentSize.height - _inputTextView.frame.size.height;
        [_inputTextView scrollRectToVisible:CGRectMake(0, offset, _inputTextView.frame.size.width, _inputTextView.frame.size.height) animated:YES];
    }
    
    
    [self textViewDidChange:_inputTextView];
}


- (void)resetTextStyle {
    //After changing text selection, should reset style.
    NSRange wholeRange = NSMakeRange(0, _inputTextView.textStorage.length);
    
    [_inputTextView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];
    [_inputTextView.textStorage removeAttribute:NSForegroundColorAttributeName range:wholeRange];
}

- (void)backDelete {
    [self.inputTextView deleteBackward];
    [self textViewDidChange:_inputTextView];
}

- (void)updateTextViewFrame {
    [self textViewDidChange:[UITextView new]];
}

- (void)changeToKeyboard {
    [self clickKeyboardBtn:self.keyboardButton];
}


@end
